<template>
<div :class="[$style.container]" @keyup.enter="onConfirm">
<el-dialog title="发布" :visible.sync="visible" width="30%">
  <el-alert title="文档发布需要通过审批" type="info" :closable="false"></el-alert>
  <el-form size="small" label-position="top" :rules="rules" :model="form" @submit.native.prevent="" ref="fm">
    <el-form-item prop="auditUserId" label="请选择审批人">
      <search-select v-model="form.auditUserId" :loader="loader"></search-select>
    </el-form-item>
  </el-form>
  <span slot="footer">
    <el-button size="small" @click="onCancel" class="px-5">取 消</el-button>
    <el-button size="small" type="primary" @click="onConfirm" :loading="submitting" class="px-5">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script lang="ts">

import { likeEntUsers } from '@/api/user'
import { startPublishDocFlow } from '@/api/doc'
import { AppModule } from '@/store'
import { Vue, Component, Prop, Emit, Ref } from 'vue-property-decorator'

@Component
export default class DocPublishModal extends Vue {
  @Ref() fm!: any

  @AppModule.State currentSpace!: any

  visible = false

  data: any = null

  resolve: ((value: any) => void) | null = null

  reject: (() => void) | null = null

  submitting = false

  form = {
    auditUserId: null
  }

  rules = {
    auditUserId: [
      { type: 'number', required: true, message: '请选择审批人' }
    ]
  }

  get loader () {
    return (keyword: string) => likeEntUsers(this.currentSpace?.ownId, keyword)
      .then(data => (data || []).map(v => Object.assign({}, v, { label: `${v.phone} (${v.name})`, value: v.userId })))
  }

  open (data: any) {
    this.data = data
    this.visible = true
    this.$nextTick(() => {
      this.fm.resetFields()
    })
    return new Promise((resolve, reject) => {
      this.resolve = resolve
      this.reject = reject
    })
  }

  onCancel () {
    this.visible = false
    if (this.reject) this.reject()
  }

  onConfirm () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      this.submitting = true
      startPublishDocFlow(this.data?.id, this.form.auditUserId as any).then(() => {
        this.visible = false
        if (this.resolve) this.resolve(null)
      }).finally(() => {
        this.submitting = false
      })
    })
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

</style>
